class StudentController {
    
    def index = { redirect(action:list,params:params) }

    // the delete, save and update actions only accept POST requests
    def allowedMethods = [delete:'POST', save:'POST', update:'POST']

    def list = {
        def student = session.searchStudent
        if (!params.max && !params.order) {
            student = new Student(params.findAll({k, v -> "" != v}))
            session.searchStudent = student
        }
        if (!params.max) params.max = 10
        [ student:student,
          studentList:Student.findAllEx(student, params),
          total:Student.countEx(student)]
    }

    def show = {
        def student = Student.get( params.id )

        if(!student) {
            flash.message = "student.not.found"
            flash.args = [params.id]
            flash.defaultMessage = "Student not found with id ${params.id}"
            redirect(action:list)
        }
        else { return [ student : student ] }
    }

    def delete = {
        def student = Student.get( params.id )
        if(student) {
            student.delete()
            flash.message = "student.deleted"
            flash.args = [params.id]
            flash.defaultMessage = "Student ${params.id} deleted"
            redirect(action:list)
        }
        else {
            flash.message = "student.not.found"
            flash.args = [params.id]
            flash.defaultMessage = "Student not found with id ${params.id}"
            redirect(action:list)
        }
    }

    def edit = {
        def student = Student.get( params.id )

        if(!student) {
            flash.message = "student.not.found"
            flash.args = [params.id]
            flash.defaultMessage = "Student not found with id ${params.id}"
            redirect(action:list)
        }
        else {
            return [ student : student ]
        }
    }

    def update = {
        def student = Student.get( params.id )
        def dc = grailsApplication.getDomainClass("Student")
        Student.hasMany.each { k, v ->
        	def prop = dc.getPropertyByName(k)
	        if ((prop.manyToMany && prop.owningSide) || (prop.oneToMany && !prop.otherSide)) {
	    		def otherSideClass = prop.referencedPropertyType
	    		def name = prop.name
	    		def methodName = name[0].toUpperCase() + (name.size() ? name[1..name.size() - 1] : '')
        		def ids = params."${k}\$"?.id
        		ids = (ids?.class == String ? [ids] : ids?.toList()).collect({Long.valueOf(it)})
        		
   				def dels = student."${k}"?.id - ids
        		def adds = ids - dels
				dels.each { id ->
					student."removeFrom${methodName}"(otherSideClass.get(Long.valueOf(id)))
				}
				adds.each { id ->
					student."addTo${methodName}"(otherSideClass.get(Long.valueOf(id)))
				}
        	}
        }
        	
        if(student) {
            student.properties = params
            if(!student.hasErrors() && student.save()) {
                flash.message = "student.updated"
                flash.args = [params.id]
                flash.defaultMessage = "Student ${params.id} updated"

                Student.hasMany.each { k, v ->
                	def prop = dc.getPropertyByName(k)
                	if (prop.manyToMany && !prop.owningSide) {
        	    		def otherSideClass = prop.referencedPropertyType
        	    		def name = prop.otherSide.name
        	    		def methodName = name[0].toUpperCase() + name[1..name.size() - 1]
                		def ids = params."${k}\$"?.id
                		ids = (ids?.class == String ? [ids] : ids?.toList()).collect({Long.valueOf(it)})
                		
           				def dels = student."${k}"?.id - ids
                		def adds = ids - dels
        				dels.each { id ->
        				otherSideClass.get(Long.valueOf(id))."removeFrom${methodName}"(student).save()
        				}
        				adds.each { id ->
        					otherSideClass.get(Long.valueOf(id))."addTo${methodName}"(student).save()
        				}
                	}
                }
                	
                redirect(action:show,id:student.id)
            }
            else {
                render(view:'edit',model:[student:student])
            }
        }
        else {
            flash.message = "student.not.found"
            flash.args = [params.id]
            flash.defaultMessage = "Student not found with id ${params.id}"
            redirect(action:edit,id:params.id)
        }
    }

    def create = {
        def student = new Student()
        student.properties = params
        return ['student':student]
    }

    def save = {
        def student = new Student(params)

        def dc = grailsApplication.getDomainClass("Student")
        Student.hasMany.each { k, v ->
        	def prop = dc.getPropertyByName(k)
	        if ((prop.manyToMany && prop.owningSide) || (prop.oneToMany && !prop.otherSide)) {
	    		def otherSideClass = prop.referencedPropertyType
	    		def name = prop.name
	    		def methodName = name[0].toUpperCase() + name[1..name.size() - 1]
        		def ids = params."${k}\$"?.id
        		ids = (ids?.class == String ? [ids] : ids?.toList()).collect({Long.valueOf(it)})
				ids?.each { id ->
					student."addTo${methodName}"(otherSideClass.get(Long.valueOf(id)))
				}
	       	}
        }
        
        if(!student.hasErrors() && student.save()) {
            flash.message = "student.created"
            flash.args = ["${student.id}"]
            flash.defaultMessage = "Student ${student.id} created"

            Student.hasMany.each { k, v ->
            	def prop = dc.getPropertyByName(k)
            	if (prop.manyToMany && !prop.owningSide) {
    	    		def otherSideClass = prop.referencedPropertyType
    	    		def name = prop.otherSide.name
    	    		def methodName = name[0].toUpperCase() + (name.size() ? name[1..name.size() - 1] : '')
            		def ids = params."${k}\$"?.id
            		ids = (ids?.class == String ? [ids] : ids?.toList()).collect({Long.valueOf(it)})
    				ids?.each { id ->
    					otherSideClass.get(Long.valueOf(id))."addTo${methodName}"(student).save()
    				}
            	}
            }
        	
            redirect(action:show,id:student.id)
        }
        else {
            render(view:'create',model:[student:student])
        }
    }
}